package com.cyzy.controller;


import com.cyzy.dto.ResponseDto;
import com.cyzy.utils.AliyunOrcUtil;
import com.cyzy.utils.MultipartFileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Map;

@RestController
@RequestMapping("/recognition")
public class RecognitionController {

    @Autowired
    private AliyunOrcUtil aliyunOcrUtil;
    @Autowired
    private MultipartFileUtil multipartFileUtil;

    @PostMapping("/uploadIdNum")
    public ResponseDto uploadIdNum(@RequestParam("file") MultipartFile file){
        if (file.isEmpty()) {
            return ResponseDto.fail("上传的文件为空");
        }
        try {
            // 保存上传的文件
            String filePath = multipartFileUtil.saveFile(file);
            // 调用阿里云 OCR 服务进行身份证识别
            Map<String, Object> result = aliyunOcrUtil.recognitionIdNum(filePath);
            // 删除临时文件
            Files.deleteIfExists(Paths.get(filePath));
            return ResponseDto.ok(result);
        } catch (Exception e) {
            return ResponseDto.fail("身份证识别失败: " + e.getMessage());
        }
    }

    @PostMapping("/uploadDrivingLicenseImg")
    public ResponseDto uploadDrivingLicenseImg(@RequestParam("file") MultipartFile file){
        if (file.isEmpty()) {
            return ResponseDto.fail("上传的文件为空");
        }
        try {
            // 保存上传的文件
            String filePath = multipartFileUtil.saveFile(file);
            // 调用阿里云 OCR 服务进行驾驶证识别
            Map<String, Object> result = aliyunOcrUtil.recognitionDriversLicense(filePath);
            // 删除临时文件
            Files.deleteIfExists(Paths.get(filePath));
            return ResponseDto.ok(result);
        } catch (Exception e) {
            return ResponseDto.fail("驾驶证识别失败: " + e.getMessage());
        }
    }

    @PostMapping("/uploadPermitImg")
    public ResponseDto uploadPermitImg(@RequestParam("file") MultipartFile file){
        if (file.isEmpty()) {
            return ResponseDto.fail("上传的文件为空");
        }
        try {
            // 保存上传的文件
            String filePath = multipartFileUtil.saveFile(file);
            // 调用阿里云 OCR 服务进行行驶证识别
            Map<String, Object> result = aliyunOcrUtil.recognitionPermit(filePath);
            // 删除临时文件
            Files.deleteIfExists(Paths.get(filePath));
            return ResponseDto.ok(result);
        } catch (Exception e) {
            return ResponseDto.fail("行驶证识别失败: " + e.getMessage());
        }
    }
}
